/*  
* Copyright (c) 2015-2026 LeeSon Ltd. All Rights Reserved.  
* LeeSon  QQ:25901875
*/ 
package com.leeson.portal.core.listener;

import java.net.InetAddress;
import java.util.Date;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.leeson.portal.core.model.Config;
import com.leeson.portal.core.model.OnlineMap;
import com.leeson.portal.core.service.InterfaceControl;
import com.leeson.portal.manage.domain.LogRecord;
import com.leeson.portal.manage.service.LogRecordService;

public class CopyOfCheckOnline extends Thread{
	private String host;
	private String username;
	private Config config=Config.getInstance();

	public CopyOfCheckOnline(String host,String username) {
		this.host = host;
		this.username=username;
	}
	
	public void run() {
		boolean state = false;
		int count = 0;

		while (!state) {
			state = doPing(host);
			if (state) {
				System.out.println(host + "在线！！");
			} else {
				System.out.println(host + "超时！！");
			}
			count++;
			if (count >= Integer.parseInt(config.getUserHeartCount())) {
				System.out.println(host + "不在线！！停止计费！！发送下线请求！！");
				Boolean info = InterfaceControl.Method("PORTAL_LOGINOUT",
						username, "password", host);
				if (info == true) {
					OnlineMap onlineMap=OnlineMap.getInstance();
					onlineMap.getOnlineUserMap().remove(host);
					System.out.println(host + "强制下线成功！！");
					
					
					ApplicationContext ac = new ClassPathXmlApplicationContext(
							"applicationContext.xml");
					LogRecord logRecord=new LogRecord();
					Date nowDate=new Date();
					logRecord.setInfo("IP:"+host+",用户："+username+",心跳检测超时，强制下线成功!");
					logRecord.setRec_date(nowDate);
					LogRecordService logRecordService=(LogRecordService) ac.getBean("logRecordServiceImpl");
					logRecordService.save(logRecord);
				}
				break;
			}
		}

	}
	
	public boolean doPing(String host) {

		boolean a = false;
		int timeOut = Integer.parseInt(config.getTimeoutSec()); // I recommend 3 seconds at least
		try {
			a = InetAddress.getByName(host).isReachable(timeOut*1000);
		} catch (Exception e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
			return a;
		}
		return a;
	}

	

}
